package org.windchill955.processplan;

import org.windchill955.common.ToolUtil;
import wt.fc.ObjectToObjectLink;
import wt.vc.Mastered;

import java.util.ArrayList;
import java.util.List;

/**
 * link节点
 * <p>
 * 这个和ObjectToObjectLink的区别是，roleB是最新小版本，而不是master对象
 *
 * @author pyk13
 * @version 0.1
 */
public class Node {
    private ObjectToObjectLink link;
    private Object roleBObject;
    private Node parentNode;
    private Object roleAObject;

    private Object object;

    private List<Node> children = new ArrayList<>(10);

    public Node(Object roleBObject) {
        this.roleBObject = roleBObject;
    }

    public Node(ObjectToObjectLink link, Object roleBObject) {
        this.link = link;
        this.roleAObject = link.getRoleAObject();
        this.roleBObject = roleBObject;
    }

    public Node(ObjectToObjectLink link, Object roleBObject, Node parentNode) {
        this.link = link;
        this.roleAObject = link.getRoleAObject();
        this.roleBObject = roleBObject;
        this.parentNode = parentNode;
        this.parentNode.children.add(this);
    }

    public ObjectToObjectLink getLink() {
        return link;
    }

    public void setLink(ObjectToObjectLink link) {
        this.link = link;
    }

    public Object getRoleBObject() {
        return roleBObject;
    }

    public void setRoleBObject(Object roleBObject) {
        this.roleBObject = roleBObject;
    }

    public Node getParentNode() {
        return parentNode;
    }

    public void setParentNode(Node parentNode) {
        if (this.parentNode != null) {
            //从旧的父节点移除当前子节点
            this.parentNode.children.removeIf(n -> n.equals(this));
        }
        this.parentNode = parentNode;
        this.parentNode.children.add(this);
    }

    public Object getRoleAObject() {
        return roleAObject;
    }

    public List<Node> getChildren() {
        return children;
    }

    public void setChildren(List<Node> children) {
        this.children = children;
    }

    public Object getObject() {
        if (object == null) {
            if (roleBObject instanceof Mastered) {
                object = ToolUtil.getLatestPersistable((Mastered) roleBObject);
            } else {
                object = roleBObject;
            }
        }
        return object;
    }
}
